<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/9/16
 * Time: 14:03
 */
namespace App\Api\Controllers\DaDa;


use App\Models\DadaConfig;
use App\Models\DadaMerchant;
use App\Models\DadaOrder;
use App\Models\DadaStore;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AddController extends BaseController
{
    /**
     * 注册商户
     *
     * 商户注册接口,并完成与该商户的绑定.生成的初始化密码会以短信形式发送给注册手机号
     * @param Request $request
     * @return string
     */
    public function merchantAdd(Request $request)
    {
        $token = $this->parseToken();
        $config_id = $request->post('configId', '1234'); //服务商配置id
        $store_id = $request->post('storeId', ''); //门店id
        $mobile = $request->post('mobile', ''); //String,是,注册商户手机号,用于登陆商户后台
        $city_name = $request->post('cityName', ''); //String,是,商户城市名称(如,上海)
        $enterprise_name = $request->post('enterpriseName', ''); //String,是,企业全称
        $enterprise_address = $request->post('enterpriseAddress', ''); //String,是,企业地址
        $contact_name = $request->post('contactName', ''); //String,是,联系人姓名
        $contact_phone = $request->post('contactPhone', ''); //String,是,联系人电话
        $email = $request->post('email', ''); //String,是,邮箱地址

        $check_data = [
            'storeId' => '系统门店id',
            'mobile' => '注册商户手机号',
            'cityName' => '商户城市名称',
            'enterpriseName' => '企业全称',
            'enterpriseAddress' => '企业地址',
            'contactName' => '联系人姓名',
            'contactPhone' => '联系人电话',
            'email' => '邮箱地址'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '达达配送参数未配置'
            ]);
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $source_id = ''; //商户id

        try {
            $requestData = [
                'mobile' => $mobile,
                'city_name' => $city_name,
                'enterprise_name' => $enterprise_name,
                'enterprise_address' => $enterprise_address,
                'contact_name' => $contact_name,
                'contact_phone' => $contact_phone,
                'email' => $email
            ];
            Log::info('达达配送-注册商户');
            Log::info($requestData);
            $res_arr = $this->http_post($this->merchant_add, $app_key, $app_secret, $source_id, $requestData); //1-成功 2-失败
            Log::info($res_arr);

            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    $update_data = [
                        'source_id' => $result_arr['result'],
                        'status' => 1
                    ];
                    if ($config_id) $update_data['config_id'] = $config_id;
                    $result = DadaMerchant::create($update_data);
                    if (!$result) {
                        return json_encode([
                            'status' => '2',
                            'message' => '注册商户,创建达达商户失败'
                        ]);
                    }

                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 新增配送单
     *
     * 在测试环境，使用统一商户和门店进行发单。其中，商户id：73753，门店编号：11047059
     * @param Request $request
     * @return string
     */
    public function orderAddOrder(Request $request)
    {
        $token = $this->parseToken();
        $config_id = $request->post('configId', '1234'); //服务商配置id
        $store_id = $request->post('storeId', ''); //门店id
        $city_code = $request->post('cityCode', ''); //是，订单所在城市的code（查看各城市对应的code值）
        $cargo_price = $request->post('cargoPrice', ''); //Double，是，订单金额
        $is_prepay = $request->post('isPrepay', ''); //Integer，是，是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
        $receiver_name = $request->post('receiverName', ''); //String，是，收货人姓名
        $receiver_address = $request->post('receiverAddress', ''); //String，是，收货人地址
        $receiver_lat = $request->post('receiverLat', ''); //Double，是，收货人地址纬度（高德坐标系，若是其他地图经纬度需要转化成高德地图经纬度，高德地图坐标拾取器）
        $receiver_lng = $request->post('receiverLng', ''); //Double，是，收货人地址经度（高德坐标系，若是其他地图经纬度需要转化成高德地图经纬度，高德地图坐标拾取器)
        $cargo_weight = $request->post('cargoWeight', ''); //Double，是，订单重量（单位：Kg）
        $sku_name = $request->post('skuName', ''); //String，是，商品名称，限制长度128
        $src_product_no = $request->post('srcProductNo', ''); //String，是，商品编码，限制长度64
        $count = $request->post('count', ''); //Double，是，商品数量，精确到小数点后两位

        $receiver_phone = $request->post('receiverPhone', ''); //String，否，收货人手机号（手机号和座机号必填一项）
        $receiver_tel = $request->post('receiverTel', ''); //String，否，收货人座机号（手机号和座机号必填一项）
        $tips = $request->post('tips', ''); //Double，否，小费（单位：元，精确小数点后一位）
        $info = $request->post('info', ''); //String，否，订单备注
        $cargo_type = $request->post('cargoType', ''); //Integer，否，订单商品类型：食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29,火锅-51,其他-5
        $cargo_num = $request->post('cargoNum', ''); //Integer，否，订单商品数量
        $invoice_title = $request->post('invoiceTitle', ''); //String，否，发票抬头
        $origin_mark = $request->post('originMark', ''); //String，否，订单来源标示（只支持字母，最大长度为10）
        $origin_mark_no = $request->post('originMark_no', ''); //String，否，订单来源编号，最大长度为30，该字段可以显示在骑士APP订单详情页面，示例：origin_mark_no:"#京东到家#1"；达达骑士APP看到的是：#京东到家#1
        $is_use_insurance = $request->post('isUseInsurance', ''); //Integer，否，是否使用保价费（0：不使用保价，1：使用保价； 同时，请确保填写了订单金额（cargo_price））；商品保价费(当商品出现损坏，可获取一定金额的赔付)；保费=配送物品实际价值*费率（5‰），配送物品价值及最高赔付不超过10000元， 最高保费为50元（物品价格最小单位为100元，不足100元部分按100元认定，保价费向上取整数， 如：物品声明价值为201元，保价费为300元*5‰=1.5元，取整数为2元。）；若您选择不保价，若物品出现丢失或损毁，最高可获得平台30元优惠券。（优惠券直接存入用户账户中）
        $is_finish_code_needed = $request->post('isFinishCodeNeeded', ''); //Integer，否，收货码（0：不需要；1：需要。收货码的作用是：骑手必须输入收货码才能完成订单妥投）
        $delay_publish_time = $request->post('delayPublishTime', ''); //Integer，否，预约发单时间（预约时间unix时间戳(10位),精确到分;整分钟为间隔，并且需要至少提前5分钟预约，可以支持未来3天内的订单发预约单。）
        $is_direct_delivery = $request->post('isDirectDelivery', ''); //Integer，否，是否选择直拿直送（0：不需要；1：需要。选择直拿直送后，同一时间骑士只能配送此订单至完成，同时，也会相应的增加配送费用）
        $unit = $request->post('unit', ''); //String，否，商品单位，默认：件
        $pick_up_pos = $request->post('pickUpPos', ''); //String，否，货架信息,该字段可在骑士APP订单备注中展示
        $out_trade_no = $request->post('out_trade_no', ''); //系统支付订单号

        $check_data = [
            'storeId' => '门店id',
            'cityCode' => '订单所在城市的code',
            'cargoPrice' => '订单金额',
            'isPrepay' => '是否需要垫付',
            'receiverName' => '收货人姓名',
            'receiverAddress' => '收货人地址',
            'receiverLat' => '收货人地址纬度',
            'receiverLng' => '收货人地址经度',
            'cargoWeight' => '订单重量',
            'skuName' => '商品名称',
            'srcProductNo' => '商品编码',
            'count' => '商品数量',
            'out_trade_no' => '系统支付订单号'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '达达配送参数未配置'
            ]);
        }

        $dada_merchant_obj = DadaMerchant::where('store_id', $store_id)
            ->where('status', 1)
            ->first();
        if (!$dada_merchant_obj) {
            return json_encode([
                'status' => '2',
                'message' => '达达商户尚未创建或状态异常'
            ]);
        }

        $dada_store_obj = DadaStore::where('store_id', $store_id)
//            ->where('status', 1) //暂时达达平台创建，默认是成功的
            ->first();
        if (!$dada_store_obj) {
            return json_encode([
                'status' => '2',
                'message' => '达达门店尚未创建或状态异常'
            ]);
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $shop_no = $dada_store_obj->shop_no;	//String，是，门店编号，门店创建后可在门店列表和单页查看
        $source_id = $dada_merchant_obj->source_id ? $dada_merchant_obj->source_id : $config_obj->source_id; //

        $origin_id = $this->createOrderId();

        try {
            $requestData = [
                'store_id' => $store_id,
                'shop_no' => $shop_no, //
                'origin_id' => $origin_id, //String，是，第三方订单ID
                'city_code' => $city_code,
                'cargo_price' => $cargo_price,
                'is_prepay' => $is_prepay,
                'receiver_name' => $receiver_name,
                'receiver_address' => $receiver_address,
                'receiver_lat' => $receiver_lat,
                'receiver_lng' => $receiver_lng,
                'callback' => url('api/dada/callBackOrder'), //String，是，回调URL
                'cargo_weight' => $cargo_weight,
                'out_trade_no' => $out_trade_no,
            ];
            if ($receiver_phone) $requestData['receiver_phone'] = $receiver_phone;
            if ($receiver_tel) $requestData['receiver_tel'] = $receiver_tel;
            if ($tips) $requestData['tips'] = $tips;
            if ($info) $requestData['info'] = $info;
            if ($cargo_type) $requestData['cargo_type'] = $cargo_type;
            if ($cargo_num) $requestData['cargo_num'] = $cargo_num;
            if ($invoice_title) $requestData['invoice_title'] = $invoice_title;
            if ($origin_mark) $requestData['origin_mark'] = $origin_mark;
            if ($origin_mark_no) $requestData['origin_mark_no'] = $origin_mark_no;
            if ($is_use_insurance) $requestData['is_use_insurance'] = $is_use_insurance;
            if ($is_finish_code_needed) $requestData['is_finish_code_needed'] = $is_finish_code_needed;
            if ($delay_publish_time) $requestData['delay_publish_time'] = $delay_publish_time;
            if ($is_direct_delivery) $requestData['is_direct_delivery'] = $is_direct_delivery;
            if ($sku_name && $src_product_no && $count) {
                $product_list = [
                    'sku_name' => $sku_name,
                    'src_product_no' => $src_product_no,
                    'count' => number_format($count, 3)
                ];

                if ($unit) $product_list['unit'] = $unit;
//                $requestData['product_list'] = $product_list; //Object	否，订单商品明细
            }
            if ($pick_up_pos) $requestData['pick_up_pos'] = $pick_up_pos;

            //资料入库
            $tableObj = DadaOrder::create($requestData);
            if (!$tableObj) {
                return json_encode([
                    'status' => '2',
                    'message' => '写入达达配送订单表失败'
                ]);
            }
            unset($requestData['store_id']);

            Log::info('达达配送-新增配送单');
            Log::info($requestData);
            $res_arr = $this->http_post($this->addOrder, $app_key, $app_secret, $source_id, $requestData); //1-成功 2-失败
            Log::info($res_arr);

            //成功,更新达达配送订单表
            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    $update_data = [
                        'distance' => $result_arr['result']['distance'],
                        'fee' => $result_arr['result']['fee'],
                        'deliver_fee' => $result_arr['result']['deliverFee'],
                        'status' => 1
                    ];
                    if (isset($result_arr['result']['couponFee'])) $update_data['coupon_fee'] = $result_arr['result']['couponFee']; //优惠券费用(单位：元)
                    if (isset($result_arr['result']['tips'])) $update_data['tips'] = $result_arr['result']['tips']; //小费(单位：元)
                    if (isset($result_arr['result']['insuranceFee'])) $update_data['insurance_fee'] = $result_arr['result']['insuranceFee']; //保价费(单位：元)
                    $result = DadaOrder::where('origin_id', $origin_id)->update($update_data);
                    if (!$result) {
                        return json_encode([
                            'status' => '2',
                            'message' => '更新系统达达订单失败'
                        ]);
                    }

                    $result_arr['result']['origin_id'] = $origin_id; //系统订单号
                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 重新发布订单
     *
     * 在调用新增订单后，订单被取消、投递异常（妥投异常之物品返回完成=10）的情况下，调用此接口，可以在达达平台重新发布订单
     * @param Request $request
     * @return string
     */
    public function reAddOrder(Request $request)
    {
        $token = $this->parseToken();
        $config_id = $request->post('configId', '1234'); //服务商配置id
        $store_id = $request->post('storeId', ''); //系统门店id
        $city_code = $request->post('cityCode', ''); //是，订单所在城市的code（查看各城市对应的code值）
        $cargo_price = $request->post('cargoPrice', ''); //Double，是，订单金额
        $is_prepay = $request->post('isPrepay', ''); //Integer，是，是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
        $receiver_name = $request->post('receiverName', ''); //String，是，收货人姓名
        $receiver_address = $request->post('receiverAddress', ''); //String，是，收货人地址
        $receiver_lat = $request->post('receiverLat', ''); //Double，是，收货人地址纬度（高德坐标系，若是其他地图经纬度需要转化成高德地图经纬度，高德地图坐标拾取器）
        $receiver_lng = $request->post('receiverLng', ''); //Double，是，收货人地址经度（高德坐标系，若是其他地图经纬度需要转化成高德地图经纬度，高德地图坐标拾取器)
        $cargo_weight = $request->post('cargoWeight', ''); //Double，是，订单重量（单位：Kg）
        $sku_name = $request->post('skuName', ''); //String，是，商品名称，限制长度128
        $src_product_no = $request->post('srcProductNo', ''); //String，是，商品编码，限制长度64
        $count = $request->post('count', ''); //Double，是，商品数量，精确到小数点后两位

        $receiver_phone = $request->post('receiverPhone', ''); //String，否，收货人手机号（手机号和座机号必填一项）
        $receiver_tel = $request->post('receiverTel', ''); //String，否，收货人座机号（手机号和座机号必填一项）
        $tips = $request->post('tips', ''); //Double，否，小费（单位：元，精确小数点后一位）
        $info = $request->post('info', ''); //String，否，订单备注
        $cargo_type = $request->post('cargoType', ''); //Integer，否，订单商品类型：食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29,火锅-51,其他-5
        $cargo_num = $request->post('cargoNum', ''); //Integer，否，订单商品数量
        $invoice_title = $request->post('invoiceTitle', ''); //String，否，发票抬头
        $origin_mark = $request->post('originMark', ''); //String，否，订单来源标示（只支持字母，最大长度为10）
        $origin_mark_no = $request->post('originMark_no', ''); //String，否，订单来源编号，最大长度为30，该字段可以显示在骑士APP订单详情页面，示例：origin_mark_no:"#京东到家#1"；达达骑士APP看到的是：#京东到家#1
        $is_use_insurance = $request->post('isUseInsurance', ''); //Integer，否，是否使用保价费（0：不使用保价，1：使用保价； 同时，请确保填写了订单金额（cargo_price））；商品保价费(当商品出现损坏，可获取一定金额的赔付)；保费=配送物品实际价值*费率（5‰），配送物品价值及最高赔付不超过10000元， 最高保费为50元（物品价格最小单位为100元，不足100元部分按100元认定，保价费向上取整数， 如：物品声明价值为201元，保价费为300元*5‰=1.5元，取整数为2元。）；若您选择不保价，若物品出现丢失或损毁，最高可获得平台30元优惠券。（优惠券直接存入用户账户中）
        $is_finish_code_needed = $request->post('isFinishCodeNeeded', ''); //Integer，否，收货码（0：不需要；1：需要。收货码的作用是：骑手必须输入收货码才能完成订单妥投）
        $delay_publish_time = $request->post('delayPublishTime', ''); //Integer，否，预约发单时间（预约时间unix时间戳(10位),精确到分;整分钟为间隔，并且需要至少提前5分钟预约，可以支持未来3天内的订单发预约单。）
        $is_direct_delivery = $request->post('isDirectDelivery', ''); //Integer，否，是否选择直拿直送（0：不需要；1：需要。选择直拿直送后，同一时间骑士只能配送此订单至完成，同时，也会相应的增加配送费用）
        $unit = $request->post('unit', ''); //String，否，商品单位，默认：件
        $pick_up_pos = $request->post('pickUpPos', ''); //String，否，货架信息,该字段可在骑士APP订单备注中展示

        $check_data = [
            'storeId' => '系统门店id',
            'cityCode' => '订单所在城市的code',
            'cargoPrice' => '订单金额',
            'isPrepay' => '是否需要垫付',
            'receiverName' => '收货人姓名',
            'receiverAddress' => '收货人地址',
            'receiverLat' => '收货人地址纬度',
            'receiverLng' => '收货人地址经度',
            'cargoWeight' => '订单重量',
            'skuName' => '商品名称',
            'srcProductNo' => '商品编码',
            'count' => '商品数量'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '达达配送参数未配置'
            ]);
        }

        $dada_merchant_obj = DadaMerchant::where('store_id', $store_id)
            ->where('status', 1)
            ->first();
        if (!$dada_merchant_obj) {
            return json_encode([
                'status' => '2',
                'message' => '达达商户尚未创建或状态异常'
            ]);
        }

        $dada_store_obj = DadaStore::where('store_id', $store_id)
//            ->where('status', 1) //暂时达达平台创建，默认是成功的
            ->first();
        if (!$dada_store_obj) {
            return json_encode([
                'status' => '2',
                'message' => '达达门店尚未创建或状态异常'
            ]);
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $shop_no = $dada_store_obj->shop_no;	//String，是，门店编号，门店创建后可在门店列表和单页查看
        $source_id = $dada_merchant_obj->source_id ?? $config_obj->source_id; //商户id

        $origin_id = $this->createOrderId();

        try {
            $requestData = [
                'shop_no' => $shop_no, //???
                'origin_id' => $origin_id, //String，是，第三方订单ID
                'city_code' => $city_code,
                'cargo_price' => $cargo_price,
                'is_prepay' => $is_prepay,
                'receiver_name' => $receiver_name,
                'receiver_address' => $receiver_address,
                'receiver_lat' => $receiver_lat,
                'receiver_lng' => $receiver_lng,
                'callback' => url('api/dada/callBackOrder'), //String，是，回调URL
                'cargo_weight' => $cargo_weight
            ];
            if ($receiver_phone) $requestData['receiver_phone'] = $receiver_phone;
            if ($receiver_tel) $requestData['receiver_tel'] = $receiver_tel;
            if ($tips) $requestData['tips'] = $tips;
            if ($info) $requestData['info'] = $info;
            if ($cargo_type) $requestData['cargo_type'] = $cargo_type;
            if ($cargo_num) $requestData['cargo_num'] = $cargo_num;
            if ($invoice_title) $requestData['invoice_title'] = $invoice_title;
            if ($origin_mark) $requestData['origin_mark'] = $origin_mark;
            if ($origin_mark_no) $requestData['origin_mark_no'] = $origin_mark_no;
            if ($is_use_insurance) $requestData['is_use_insurance'] = $is_use_insurance;
            if ($is_finish_code_needed) $requestData['is_finish_code_needed'] = $is_finish_code_needed;
            if ($delay_publish_time) $requestData['delay_publish_time'] = $delay_publish_time;
            if ($is_direct_delivery) $requestData['is_direct_delivery'] = $is_direct_delivery;
            if ($sku_name && $src_product_no && $count) {
                $product_list = [ //Object	否，订单商品明细
                    'sku_name' => $sku_name,
                    'src_product_no' => $src_product_no,
                    'count' => $count
                ];
                if ($unit) $product_list['unit'] = $unit;
                $requestData['product_list'] = json_encode($product_list);
            }
            if ($pick_up_pos) $requestData['pick_up_pos'] = $pick_up_pos;

            //资料入库
            $tableObj = DadaOrder::create($requestData);
            if (!$tableObj) {
                return json_encode([
                    'status' => '2',
                    'message' => '写入达达配送订单表失败'
                ]);
            }
//            unset($requestData['store_id']);

            Log::info('达达配送-重新发布订单');
            Log::info($requestData);
            $res_arr = $this->http_post($this->reAddOrder, $app_key, $app_secret, $source_id, $requestData); //1-成功 2-失败
            Log::info($res_arr);

            //成功,更新达达配送订单表
            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    $update_data = [
                        'distance' => $result_arr['result']['distance'],
                        'fee' => $result_arr['result']['fee'],
                        'deliver_fee' => $result_arr['result']['deliverFee'],
                        'status' => 1
                    ];
                    if (isset($result_arr['result']['couponFee'])) $update_data['coupon_fee'] = $result_arr['result']['couponFee']; //优惠券费用(单位：元)
                    if (isset($result_arr['result']['tips'])) $update_data['tips'] = $result_arr['result']['tips']; //小费(单位：元)
                    if (isset($result_arr['result']['insuranceFee'])) $update_data['insurance_fee'] = $result_arr['result']['insuranceFee']; //保价费(单位：元)

                    $result_obj = DadaOrder::where('id', $tableObj)->first();
                    if ($result_obj) {
                        $result = $result_obj->update($update_data);
                        if (!$result) {
                            return json_encode([
                                'status' => '2',
                                'message' => '重新发布订单,更新达达订单失败'
                            ]);
                        }
                    }

                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 妥投异常之物品返回完成
     *
     * 订单妥投异常后，订单状态变为9，骑士将物品进行返还，如果商家确认收到物品后，可以使用该 接口进行确认，订单状态变成10，同时订单终结
     * @param Request $request
     * @return string
     */
    public function orderConfirmGoods(Request $request)
    {
        $token = $this->parseToken();
        $config_id = $request->post('configId', '1234'); //服务商配置id
        $store_id = $request->post('storeId', ''); //门店id
        $order_id = $request->post('orderId', ''); //String，是，第三方订单编号

        $check_data = [
            'orderId' => '第三方订单编号'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        $result_obj = DadaOrder::where('origin_id', $order_id)->first();
        if (!$result_obj) {
            return json_encode([
                'status' => '2',
                'message' => '妥投异常之物品返回完成,未找到该笔订单'
            ]);
        }
        if ($result_obj->status_code != 9) {
            return json_encode([
                'status' => '2',
                'message' => '妥投异常之物品返回完成,状态异常'
            ]);
        }

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '达达配送参数未配置'
            ]);
        }

        $dada_merchant_obj = DadaMerchant::where('store_id', $store_id)
            ->where('status', 1)
            ->first();
        if (!$dada_merchant_obj) {
            return json_encode([
                'status' => '2',
                'message' => '达达商户尚未创建'
            ]);
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $source_id = $dada_merchant_obj->source_id ? $dada_merchant_obj->source_id : ''; //商户id

        try {
            $requestData = [
                'order_id' => $order_id
            ];
            Log::info('达达配送-妥投异常之物品返回完成');
            Log::info($requestData);
            $res_arr = $this->http_post($this->reAddOrder, $app_key, $app_secret, $source_id, $requestData); //1-成功 2-失败
            Log::info($res_arr);

            //成功,更新达达配送订单表
            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    $update_data = [
                        'status_code' => 10
                    ];
                    $result = $result_obj->update($update_data);
                    if (!$result) {
                        return json_encode([
                            'status' => '2',
                            'message' => '妥投异常之物品返回完成,更新达达订单状态失败'
                        ]);
                    }

                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 消息确认
     *
     * 1.商家接受到消息后，根据不同的messageType作不同的操作
     * 2.当产生对应类型的消息时，达达开放平台会将消息推送至配置的URL地址
     * @param Request $request
     * @return string
     */
    public function messageConfirm(Request $request)
    {
        $token = $this->parseToken();
        $config_id = $request->post('configId', '1234'); //服务商配置id
        $store_id = $request->post('storeId', ''); //门店id
        $order_id = $request->post('orderId', ''); //第三方订单编号
        $message_body = $request->post('messageBody', ''); //String，是，消息内容（json字符串）

        $check_data = [
            'storeId' => '门店id',
            'orderId' => '第三方订单编号',
            'messageBody' => '消息内容'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        $result_obj = DadaOrder::where('origin_id', $order_id)->first();
        if (!$result_obj) {
            return json_encode([
                'status' => '2',
                'message' => '消息确认,未找到该笔订单'
            ]);
        }

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '消息确认,达达配送参数未配置'
            ]);
        }

        $dada_store_obj = DadaMerchant::where('store_id', $store_id)
            ->where('status', 1)
            ->first();
        if (!$dada_store_obj) {
            return json_encode([
                'status' => '2',
                'message' => '消息确认,达达商户尚未创建or状态异常'
            ]);
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $source_id = $dada_store_obj->source_id; //商户id

        try {
            $requestData = [
                'messageType' => 1,
                'messageBody' => $message_body
            ];
            Log::info('达达配送-消息确认');
            Log::info($requestData);
            $res_arr = $this->http_post($this->message_confirm, $app_key, $app_secret, $source_id, $requestData); //1-成功 2-失败
            Log::info($res_arr);

            //成功
            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    $update_data = [
                        'message_type' => 1
                    ];
                    $result = $result_obj->update($update_data);
                    if (!$result) {
                        return json_encode([
                            'status' => '2',
                            'message' => '消息确认,更新达达订单状态失败'
                        ]);
                    }

                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 门店创建
     *
     * 1. 门店编码可自定义，但必须唯一，若不填写，则系统自动生成。发单时用于确认发单门店
     * 2. 如果需要使用达达商家App发单，请设置登陆达达商家App的账号（必须手机号）和密码
     * 3. 该接口为批量接口,业务参数为数组
     * @param Request $request
     * @return string
     */
    public function shopAdd(Request $request)
    {
        $token = $this->parseToken();
        $config_id = $request->post('configId', '1234'); //服务商配置id
        $store_id = $request->post('storeId', ''); //门店id
        $station_name = $request->post('stationName', ''); //String,是,门店名称
        $business = $request->post('business', ''); //Integer,是,业务类型(食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29,火锅-51,其他-5)
        $city_name = $request->post('cityName', ''); //String,是,城市名称(如,上海)
        $area_name = $request->post('areaName', ''); //String,是,区域名称(如,浦东新区)
        $station_address = $request->post('stationAddress', ''); //String,是,门店地址
        $lng = $request->post('lng', ''); //String,是,门店经度
        $lat = $request->post('lat', ''); //String,是,门店纬度
        $contact_name = $request->post('contactName', ''); //String,是,联系人姓名
        $phone = $request->post('phone', ''); //String,是,联系人电话

        $origin_shop_id = $request->post('originShopId', ''); //String,否,门店编码,可自定义,但必须唯一;若不填写,则系统自动生成
        $id_card = $request->post('idCard', ''); //String,否,联系人身份证
        $username = $request->post('username', ''); //String,否,达达商家app账号(若不需要登陆app,则不用设置)
        $password = $request->post('password', ''); //String,否,达达商家app密码(若不需要登陆app,则不用设置)

        $check_data = [
            'stationName' => '门店名称',
            'business' => '业务类型',
            'cityName' => '城市名称',
            'areaName' => '区域名称',
            'stationAddress' => '门店地址',
            'lng' => '门店经度',
            'lat' => '门店纬度',
            'contactName' => '联系人姓名',
            'phone' => '联系人电话'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '达达配送参数未配置'
            ]);
        }

        $dada_store_obj = DadaMerchant::where('store_id', $store_id)
            ->where('status', 1)
            ->first();
        if (!$dada_store_obj) {
            return json_encode([
                'status' => '2',
                'message' => '达达商户尚未创建or状态异常'
            ]);
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $source_id = $dada_store_obj->source_id; //商户id

        try {
            $requestData = [
                'station_name' => $station_name,
                'business' => $business,
                'city_name' => $city_name,
                'area_name' => $area_name,
                'station_address' => $station_address,
                'lng' => $lng,
                'lat' => $lat,
                'contact_name' => $contact_name,
                'phone' => $phone
            ];
            if ($origin_shop_id) $requestData['origin_shop_id'] = $origin_shop_id;
            if ($id_card) $requestData['id_card'] = $id_card;
            if ($username) $requestData['username'] = $username;
            if ($password) $requestData['password'] = $password;

            $insert_data = $requestData;
            $insert_result = DadaStore::create($insert_data);
            if (!$insert_result) {
                return json_encode([
                    'status' => '2',
                    'message' => '新增门店,创建达达门店失败'
                ]);
            }

            Log::info('达达配送-批量新增门店');
            Log::info($requestData);
            $res_arr = $this->http_post($this->shop_add, $app_key, $app_secret, $source_id, [$requestData]); //1-成功 2-失败
            Log::info($res_arr);

            //成功
            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    $update_result = DadaStore::where('id', $insert_result)->update([
                        'status' => 1
                    ]);
                    if (!$update_result) {
                        return json_encode([
                            'status' => '2',
                            'message' => '批量新增门店,更新达达门店失败'
                        ]);
                    }

                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 门店更新
     *
     * 门店编码是必传参数。其他参数，需要更新则传，且不能为空。
     * @param Request $request
     * @return string
     */
    public function shopUpdate(Request $request)
    {
        $token = $this->parseToken();
        $config_id = $request->post('configId', '1234'); //服务商配置id
        $store_id = $request->post('storeId', ''); //门店id
        $origin_shop_id = $request->post('originShopId', ''); //门店编码

        $new_shop_id = $request->post('newShopId', ''); //否，新的门店编码
        $business = $request->post('business', ''); //业务类型(食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29,火锅-51,其他-5)
        $city_name = $request->post('cityName', ''); //城市名称(如,上海)
        $area_name = $request->post('areaName', ''); //区域名称(如,浦东新区)
        $station_address = $request->post('stationAddress', ''); //门店地址
        $lng = $request->post('lng', ''); //门店经度
        $lat = $request->post('lat', ''); //门店纬度
        $contact_name = $request->post('contactName', ''); //联系人姓名
        $phone = $request->post('phone', ''); //联系人电话
        $status = $request->post('status', ''); //门店状态（1-门店激活，0-门店下线）

        $check_data = [
            'originShopId' => '门店编码'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        $dada_store_obj = DadaStore::where('shop_no', $origin_shop_id)->first();
        if (!$dada_store_obj) {
            return json_encode([
                'status' => '2',
                'message' => '门店更新,没有找到门店信息'
            ]);
        }

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '门店更新,达达配送参数未配置'
            ]);
        }

        $dada_mer_obj = DadaMerchant::where('store_id', $store_id)
            ->where('status', 1)
            ->first();
        if (!$dada_mer_obj) {
            return json_encode([
                'status' => '2',
                'message' => '门店更新,达达商户尚未创建or状态异常'
            ]);
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $source_id = $dada_mer_obj->source_id; //商户id

        try {
            $requestData = [
                'origin_shop_id' => $origin_shop_id
            ];
            if ($new_shop_id) $requestData['new_shop_id'] = $new_shop_id;
            if ($business) $requestData['business'] = $business;
            if ($city_name) $requestData['city_name'] = $city_name;
            if ($area_name) $requestData['area_name'] = $area_name;
            if ($station_address) $requestData['station_address'] = $station_address;
            if ($lng) $requestData['lng'] = $lng;
            if ($lat) $requestData['lat'] = $lat;
            if ($contact_name) $requestData['contact_name'] = $contact_name;
            if ($phone) $requestData['phone'] = $phone;
            if ($status) $requestData['status'] = $status;

            Log::info('达达配送-门店更新');
            Log::info($requestData);
            $res_arr = $this->http_post($this->shop_update, $app_key, $app_secret, $source_id, $requestData); //1-成功 2-失败
            Log::info($res_arr);

            //成功
            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    $update_data = $requestData;
                    $update_result = $dada_store_obj->update($update_data);
                    if (!$update_result) {
                        return json_encode([
                            'status' => '2',
                            'message' => '门店更新,更新达达门店失败'
                        ]);
                    }

                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    //订单id,即该订单在合作方系统中的id,最长不超过32个字符
    private function createOrderId()
    {
        $order_id = 'dada_ps' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
        //dada_ps20200822142107320365404
        $result = DadaOrder::where('origin_id', $order_id)->first();
        if ($result) $this->createOrderId();

        return $order_id;
    }


}
